package cn.itcast.order.config;

import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
    /**
     * 前置拦截 获取请求头中的userId,并放入到线程当中
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        //获得请求头
        String authorization = request.getHeader("authorization");
        if(StringUtils.isNotBlank(authorization)&&!StringUtils.equals("0",authorization)){
            //存入线程
            ThreadLocalUtil.setUserId(Long.valueOf(authorization));
        }
        return super.preHandle(request,response,handler);
    }

    /**
     * 清除前线程中userId
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清楚线程数据
        ThreadLocalUtil.clear();
        super.postHandle(request,response,handler,modelAndView);
    }
}
